package com.michale.framework.config.captcha;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Michale
 * @apiNote 验证码生成工具类
 */
@Slf4j
@Component
public class CaptchaUtils {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    public Map<String, Object> creatCaptcha(String classify) {
        Map<String, Object> map ;
        try {
            map = new HashMap<>();
            String capStr , code;
            BufferedImage image;
            if ("math".equals(classify)) {
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                image = captchaProducerMath.createImage(capStr);
                map.put("capStr", capStr);
                map.put("code", code);
                map.put("image", image);
                return map;
            } else if ("char".equals(classify)) {
                capStr = code = captchaProducer.createText();
                image = captchaProducer.createImage(capStr);
                map.put("capStr", capStr);
                map.put("code", code);
                map.put("image", image);
            }
        } catch (SecurityException e) {
            throw new SecurityException("验证码业务");
        }
        return map;
    }
}